package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.mapper.CouponMapper;
import com.qianniu.napi.admin.mapper.CoupontplMemberMapper;
import com.qianniu.napi.admin.mapper.StoreMapper;
import com.qianniu.napi.admin.service.ICouponTplService;
import com.qianniu.napi.admin.service.IHdtemplateService;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 优惠券模板
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-07
 */
@RestController
public class CouponTplController {

    private static final Logger logger = LoggerFactory.getLogger(CouponTplController.class);

    @Autowired
    private ICouponTplService coupontplService;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private CoupontplMemberMapper coupontplMemberMapper;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IHdtemplateService hdtemplateService;

    @RequestMapping("/api/coupontpl/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "isadmin", required = false) Integer isadmin,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo json = new Jinfo();
        if (pageIndex == 0) pageIndex = 1;
        if (pageSize == 0) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        Wrapper<CouponTpl> wrapper = new EntityWrapper<CouponTpl>()
                .eq("mpid", ObjectUtil.getMpid());
//                .eq("state", 1);

        if (isadmin == null) wrapper.eq("uid", ObjectUtil.getUid());
        page = coupontplService.selectPage(page, wrapper);

        json.setInfo(page.getRecords());
        return json;
    }

    @RequestMapping("/api/coupontpl/yllist")
    @ResponseBody
    public Jinfo yllist(String sid) {
        Jinfo json = new Jinfo();

        Wrapper<CouponTpl> wrapper = new EntityWrapper<CouponTpl>()
                .eq("mpid", ObjectUtil.getMpid()).eq("sid", sid);

        List<CouponTpl> quans = coupontplService.selectList(wrapper);

        json.setInfo(quans);
        return json;
    }

    @RequestMapping("/api/coupontpl/add")
    @ResponseBody
    public Jinfo coupontplAdd(CouponTpl coupontpl, HttpServletRequest req) {
        Jinfo json = new Jinfo();
        // 字段校验
        coupontpl.setCreatetime(new Date());
        coupontpl.setMid(ObjectUtil.getMid());
        coupontpl.setMpid(ObjectUtil.getMpid());
        coupontpl.setUid(ObjectUtil.getUid());
        if (coupontpl.getSid() == null) coupontpl.setSid(ObjectUtil.getSid());

        if (coupontpl.getSid() != null && coupontpl.getSid() > 0) {

            Store store = storeMapper.selectById(coupontpl.getSid());
            if (store != null) coupontpl.setSname(store.getName());
            if (store != null) coupontpl.setSlogo(store.getLogo());
            if (store != null) coupontpl.setLeagueid(store.getLeagueid());
            if (coupontpl.getSlogo() == null) coupontpl.setSlogo(store.getThumb());

            coupontpl.insertOrUpdate();
            json.setInfo(coupontpl);

            if (coupontpl.getIsleague() != null && coupontpl.getIsleague().intValue() == 1) {
                Store nstore = new Store();
                nstore.setId(store.getId());
                nstore.setYouhui(coupontpl.toNameString());
                nstore.setYouhuiid(coupontpl.getId());
                nstore.setModifier(ObjectUtil.getUid());
                nstore.setModifytime(new Date());
                nstore.updateById();
            }
        }

        return json;
    }

    @RequestMapping("/api/coupontpl/addtjyl")
    @ResponseBody
    public Jinfo coupontplAddtjyl(String quanstr) {
        Jinfo json = new Jinfo();
        logger.debug("=========coupontpl/addtjyl quanstr=" + quanstr);
        List<CouponTpl> qlist = JSON.parseArray(quanstr, CouponTpl.class);
        logger.debug("=========coupontpl/addtjyl =" + JSON.toJSONString(qlist));
//        json.setInfo(coupontpl);
        if (qlist == null || qlist.size() != 2) {
            json.setMsg("参数有误");
            json.setCode(1);
            return json;
        }
        CouponTpl couponTpl1 = qlist.get(0);
        CouponTpl couponTpl2 = qlist.get(1);

        //普通券
        couponTpl1.setFenxiao(0);
        couponTpl1.setMid(ObjectUtil.getMid());
        couponTpl1.setMpid(ObjectUtil.getMpid());
        couponTpl1.setSid(ObjectUtil.getSid());
        couponTpl1.setUid(ObjectUtil.getUid());
        if (couponTpl1.getSid() == null) couponTpl1.setSid(ObjectUtil.getSid());
        Store store = storeMapper.selectById(couponTpl1.getSid());

        if (store != null) couponTpl1.setSlogo(store.getLogo());
        if (store != null) couponTpl1.setSname(store.getName());
        if (couponTpl1.getId() == null) couponTpl1.setCreatetime(new Date());
        else couponTpl1.setModifytime(new Date());
        couponTpl1.setModifier(ObjectUtil.getUid());
        couponTpl1.insertOrUpdate();

        //分享有礼
        couponTpl2.setFenxiao(1);
        couponTpl2.setMid(ObjectUtil.getMid());
        couponTpl2.setMpid(ObjectUtil.getMpid());
        if (couponTpl2.getSid() == null) couponTpl2.setSid(ObjectUtil.getSid());
        couponTpl2.setUid(ObjectUtil.getUid());

        if (store != null) couponTpl2.setSlogo(store.getLogo());
        if (store != null) couponTpl2.setSname(store.getName());
        if (couponTpl1.getId() == null) couponTpl1.setCreatetime(new Date());
        else couponTpl1.setModifytime(new Date());
        couponTpl1.setModifier(ObjectUtil.getUid());

        couponTpl2.setFanid(couponTpl1.getId());
        couponTpl2.insertOrUpdate();

        return json;
    }

    @RequestMapping("/api/coupontpl/modify")
    @ResponseBody
    public Jinfo coupontplUpdate(HttpServletRequest req,
                                 CouponTpl coupontpl) {
        Jinfo json = new Jinfo();
        coupontpl.setModifytime(new Date());
        coupontpl.setModifier(ObjectUtil.getUid());
        coupontpl.updateById();

        return json;
    }

    @RequestMapping("/api/coupontpl/detail")
    @ResponseBody
    public Jinfo getCouponTplDetailById(@RequestParam("tplid") long id) {
        Jinfo json = new Jinfo();
        CouponTpl coupontpl = coupontplService.selectById(id);
        json.setInfo(coupontpl);
        List<Coupon> users = couponMapper.selectCouponUser(id);
        json.setData(users);
        if (coupontpl.getSid() != null)
            json.setExtra(storeMapper.selectById(coupontpl.getSid()));
        return json;
    }

    @RequestMapping("/api/coupontpl/sxjia")
    @ResponseBody
    public Jinfo sxjia(@RequestParam("qid") long id, HttpServletRequest req
    ) {
        Jinfo json = new Jinfo();
        CouponTpl coupontpl = coupontplService.selectById(id);
        if (coupontpl == null) {
            json.setCode(4);
            json.setMsg("该券不存在");
            return json;
        }
        CouponTpl tpl = new CouponTpl();
        tpl.setId(coupontpl.getId());
        tpl.setState(coupontpl.getState() * -1);
        tpl.updateById();

        return json;
    }

    //商家优惠券模板
    @RequestMapping("/api/coupontpl/mlist")
    @ResponseBody
    public Jinfo coupontplMlist(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();

        Long sid = ObjectUtil.getSid();
        if (sid == null) {
            info.setMsg("当前用户不是商家，无权限查看");
            info.setCode(1);
            return info;
        }

        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        Wrapper<CouponTpl> entity = new EntityWrapper<CouponTpl>()
                .eq("sid", sid).orderBy("id", false);

        Page<CouponTpl> list = coupontplService.selectPage(page, entity);
        info.setInfo(list == null || list.getRecords() == null || list.getRecords().size() == 0 ? null : list.getRecords());

        return info;
    }

    //平台优惠券模板
    @RequestMapping("/api/coupontpl/plist")
    @ResponseBody
    public Jinfo coupontplPlist(@RequestParam(value = "sid", required = false) Long sid,
                                @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();

        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        Wrapper<CouponTpl> entity = new EntityWrapper<CouponTpl>()
                .eq("mpid", ObjectUtil.getMpid()).orderBy("id", false);
        List<CouponTpl> list = coupontplService.selectList(entity);
        info.setInfo(list);
        return info;
    }

    //平台优惠券模板
    @RequestMapping("/api/coupontpl/hyquan")
    @ResponseBody
    public Jinfo coupontplPlist(@RequestParam(value = "sid", required = false) Long sid,
                                @RequestParam(value = "level", required = false) Integer level) {
        Jinfo info = new Jinfo();
        if (sid == null) sid = ObjectUtil.getSid();
        if (sid == null) {
            info.setMsg("当前用户无权限查看");
            info.setCode(1);
            return info;
        }
        List<CoupontplMember> cmembers = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>()
                .setSqlSelect("max(mlevel) mlevel")
                .eq("sid", sid));
        int maxlevelix = cmembers.get(0) == null ? -1 : cmembers.get(0).getMlevel() - 1;

        Map<String, List<CouponTpl>> map = new HashMap<String, List<CouponTpl>>();
        int mlevel = 0;
        for (int i = 1; i <= 4; i++) {
            Wrapper<CouponTpl> entity = new EntityWrapper<CouponTpl>()
                    .eq("sid", sid)
                    .eq("mlevel", i).orderBy("id");
            List<CouponTpl> list = coupontplService.selectList(entity);
            if (list != null && list.size() > 0) mlevel++;
            map.put("hy" + i, list);
        }

        info.setInfo(map);

        info.setExtra(maxlevelix);
        return info;
    }

    @RequestMapping("/api/coupontpl/addhylb")
    @ResponseBody
    public Jinfo coupontplAddhylb(String quanstr,
                                  @RequestParam(value = "sid", required = false) Long sid) {
        Jinfo json = new Jinfo();
        logger.debug("=========coupontpl/addhylb quanstr=" + quanstr);
        List<CouponTpl> qlist = JSON.parseArray(quanstr, CouponTpl.class);

        if (qlist == null || qlist.size() == 0) {
            json.setMsg("参数有误");
            json.setCode(1);
            return json;
        }
        CouponTpl couponTpl1 = qlist.get(0);
        CouponTpl couponTpl2 = qlist.size() == 2 ? qlist.get(1) : null;

        if (sid == null) sid = ObjectUtil.getSid();
        if (sid == null) {
            json.setMsg("当前商家参数有误");
            json.setCode(1);
            return json;
        }

        //每月权益1
        couponTpl1.setMid(ObjectUtil.getMid());
        couponTpl1.setMpid(ObjectUtil.getMpid());
        couponTpl1.setLeagueid(redisService.getLeagueid(sid));
        if (couponTpl1.getSid() == null) couponTpl1.setSid(ObjectUtil.getSid());
        couponTpl1.setUid(ObjectUtil.getUid());

        Store store = storeMapper.selectById(ObjectUtil.getSid());

        if (store != null) couponTpl1.setSlogo(store.getLogo());
        if (store != null) couponTpl1.setSname(store.getName());
        if (couponTpl1.getId() == null) couponTpl1.setCreatetime(new Date());
        else couponTpl1.setModifytime(new Date());
        couponTpl1.setModifier(ObjectUtil.getUid());
        couponTpl1.insertOrUpdate();

        CoupontplMember entity = new CoupontplMember();
        entity.setTplid(couponTpl1.getId());
        CoupontplMember ctplMember1 = coupontplMemberMapper.selectOne(entity);
        if (ctplMember1 == null) {
            ctplMember1 = new CoupontplMember();
            ctplMember1.setCreatetime(new Date());
            ctplMember1.setMpid(couponTpl1.getMpid());
            ctplMember1.setSid(couponTpl1.getSid());
            ctplMember1.setLeagueid(couponTpl1.getLeagueid());
            ctplMember1.setExpire(365);//默认1年
            ctplMember1.setFatype(1);//默认每月1号发放
            ctplMember1.setJihuophone(1);//默认延长会员期限时需要手机号
        }

        ctplMember1.setTplid(couponTpl1.getId());
        ctplMember1.setMlevel(couponTpl1.getMlevel());

        ctplMember1.setNum(couponTpl1.getShareshu());//默认延长会员期限时需要手机号
        if(Strings.isNullOrEmpty(couponTpl1.getRemark()))
            ctplMember1.setMquanyi(couponTpl1.toNameString() + "x" + couponTpl1.getShareshu() + "张");//默认延长会员期限时需要手机号
        else
            ctplMember1.setMquanyi(couponTpl1.getRemark()+ "x" + couponTpl1.getShareshu());//默认延长会员期限时需要手机号
        ctplMember1.insertOrUpdate();

        //每月权益2
        if (couponTpl2 != null && couponTpl2.getType() != null) {
            ctplMember1.setCreatetime(new Date());
            couponTpl2.setMid(ObjectUtil.getMid());
            couponTpl2.setMpid(ObjectUtil.getMpid());
            couponTpl2.setLeagueid(couponTpl1.getLeagueid());

            if (couponTpl2.getSid() == null) couponTpl2.setSid(ObjectUtil.getSid());
            couponTpl2.setUid(ObjectUtil.getUid());

            if (store != null) couponTpl2.setSlogo(store.getLogo());
            if (store != null) couponTpl2.setSname(store.getName());
            if (couponTpl2.getId() == null) couponTpl1.setCreatetime(new Date());
            else couponTpl2.setModifytime(new Date());

            couponTpl2.setModifier(ObjectUtil.getUid());
            couponTpl2.insertOrUpdate();

            entity.setTplid(couponTpl2.getId());
            CoupontplMember ctplMember2 = coupontplMemberMapper.selectOne(entity);

            if (ctplMember2 == null) {
                ctplMember2 = new CoupontplMember();
                ctplMember2.setCreatetime(new Date());
                ctplMember2.setMpid(couponTpl2.getMpid());
                ctplMember2.setSid(couponTpl2.getSid());
                ctplMember2.setLeagueid(couponTpl1.getLeagueid());
                ctplMember2.setExpire(365);//默认1年
                ctplMember2.setFatype(1);//默认每月1号发放
                ctplMember2.setJihuophone(1);//默认延长会员期限时需要手机号
            }

            ctplMember2.setTplid(couponTpl2.getId());
            ctplMember2.setMlevel(couponTpl2.getMlevel());

            ctplMember2.setNum(couponTpl2.getShareshu());//默认延长会员期限时需要手机号
            if(Strings.isNullOrEmpty(couponTpl2.getRemark()))
                ctplMember2.setMquanyi(couponTpl2.toNameString() + "x" + couponTpl2.getShareshu() + "张");//默认延长会员期限时需要手机号
            else
                ctplMember2.setMquanyi(couponTpl2.getRemark()+ "x" + couponTpl1.getShareshu());//默认延长会员期限时需要手机号
            ctplMember2.insertOrUpdate();
        }

        return json;
    }


    //商家版本快速复制克隆活动
    //参数mhid:活动模板id 必填
    //参数tosid:目标商家id 选填
    @RequestMapping("/api/coupontpl/clonehd")
    @ResponseBody
    public Jinfo clonehd(Long mhid, @RequestParam(value = "tosid", required = false) Long tosid) {
        Jinfo json = new Jinfo();
        if (mhid == null) {
            json.setMsg("参数有误");
            json.setCode(1);
            return json;
        }
        logger.debug("=========coupontpl/clonehd mhid=" + mhid);
        if (tosid == null) tosid = ObjectUtil.getSid();
        if (tosid == null) {
            json.setMsg("商家参数有误");
            json.setCode(1);
            return json;
        }

        Hdtemplate hdtemplate = hdtemplateService.selectById(mhid);
        if (hdtemplate == null) {
            json.setMsg("模板参数有误");
            json.setCode(1);
            return json;
        }
        CouponTpl coupontpl = null;
        Long ywid = null;

        //优惠券||推荐有礼||红包裂变
        if (hdtemplate.getYxtype().intValue() == 14 || hdtemplate.getYxtype().intValue() == 15
                || hdtemplate.getYxtype().intValue() == 16) {
            if (hdtemplate.getGid() == null) {
                json.setMsg("优惠券参数未设置");
                json.setCode(1);
                return json;
            }

            coupontpl = coupontplService.selectById(hdtemplate.getGid());
            ywid = coupontpl.getFanid();
            if (hdtemplate.getGid() == null) {
                json.setMsg("优惠券参数有误");
                json.setCode(1);
                return json;
            }
            coupontpl.setId(null);
            coupontpl.setSid(tosid);
            coupontpl.setLeagueid(redisService.getLeagueid(tosid));

            coupontpl.setCreatetime(new Date());
            coupontpl.setUid(ObjectUtil.getUid());
            coupontpl.setModifytime(new Date());
            coupontpl.setModifier(null);

            coupontpl.setUse(0);
            coupontpl.setUsed(0);
            coupontpl.setFanshu(0);

            Store store = storeMapper.selectById(tosid);
            coupontpl.setSname(store.getName());
            coupontpl.setSlogo(store.getLogo() == null ? store.getPic() : store.getLogo());

            coupontpl.insert();
        }

        if (hdtemplate.getYxtype().intValue() == 15 && ywid != null) {

            CouponTpl coupontpl2 = coupontplService.selectById(ywid);
            if (hdtemplate.getGid() == null) {
                json.setMsg("推荐有礼优惠券参数有误");
                json.setCode(1);
                return json;
            }
            coupontpl2.setId(null);
            coupontpl2.setSid(tosid);
            coupontpl2.setLeagueid(redisService.getLeagueid(tosid));

            coupontpl2.setCreatetime(new Date());
            coupontpl2.setUid(ObjectUtil.getUid());
            coupontpl2.setModifytime(new Date());
            coupontpl2.setModifier(null);

            coupontpl2.setUse(0);
            coupontpl2.setUsed(0);
            coupontpl2.setFanshu(0);

            Store store = storeMapper.selectById(tosid);
            coupontpl2.setSname(store.getName());
            coupontpl2.setSlogo(store.getLogo() == null ? store.getPic() : store.getLogo());

            coupontpl2.insert();

            CouponTpl ncoupontpl = new CouponTpl();
            ncoupontpl.setId(coupontpl.getId());
            ncoupontpl.setFanid(coupontpl2.getId());
            coupontpl.updateById();
        }

        logger.debug("====================================coupontpl/clonehd hdtemplate=" + JSON.toJSONString(hdtemplate));
        //会员裂变
        if (hdtemplate.getYxtype().intValue() == 17) {
            List<CoupontplMember> mmlist = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>().eq("sid",hdtemplate.getSid()));
            if (mmlist == null||mmlist.size()==0) {
                json.setMsg("该商家会员裂变参数未设置");
                json.setCode(1);
                return json;
            }

            for(CoupontplMember item:mmlist){
                item.setId(null);
                item.setSid(tosid);
                item.setLeagueid(redisService.getLeagueid(tosid));
                item.setCreatetime(new Date());

                coupontpl = coupontplService.selectById(item.getTplid());
                if(coupontpl==null){
                    json.setMsg("该商家会员裂变券未设置");
                    json.setCode(1);
                    return json;
                }

                coupontpl.setId(null);
                coupontpl.setSid(tosid);
                coupontpl.setLeagueid(redisService.getLeagueid(tosid));

                coupontpl.setCreatetime(new Date());
                coupontpl.setUid(ObjectUtil.getUid());
                coupontpl.setModifytime(new Date());
                coupontpl.setModifier(null);

                coupontpl.setUse(0);
                coupontpl.setUsed(0);
                coupontpl.setFanshu(0);

                Store store = storeMapper.selectById(tosid);
                coupontpl.setSname(store.getName());
                coupontpl.setSlogo(store.getLogo() == null ? store.getPic() : store.getLogo());

                coupontpl.insert();

                item.setTplid(coupontpl.getId());
                item.insert();
            }
        }

        return json;
    }

}
